#include"heap.h"

void HPInit(HP* php)
{
	assert(php);

	php->a = (HPDataType*)malloc(sizeof(HPDataType) * 4);
	if (php->a == NULL)
	{
		perror("malloc fail");
		return;
	}
	php->size = 0;
	php->capacity = 4;
}

void HPDestroy(HP* php)
{
	assert(php);

	free(php->a);
	php->size = 0;
	php->capacity = 0;
}

void swap(HPDataType* v1, HPDataType* v2)
{
	HPDataType tmp = *v1;
	*v1 = *v2;
	*v2 = tmp;
}

void AdJustUp(HPDataType* a,int child)
{
	int parent = (child - 1) / 2;
	while (child > 0)
	{
		if (a[child] > a[parent])
		{
			swap(&a[child], &a[parent]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else
		{
			break;
		}
	}
}

void HPPush(HP* php, HPDataType x)
{
	assert(php);
	if (php->size == php->capacity)
	{
		HPDataType* tmp = (HPDataType*)realloc(php->a,sizeof(HPDataType) * (php->capacity)*2);
		if (tmp == NULL)
		{
			perror("realloc fail");
			return;
		}
		php->a = tmp;
		php->capacity *= 2;
	}
	php->a[php->size] = x;
	php->size++;

	AdJustUp(php->a, php->size - 1);
}

void AdJustDowm(HPDataType* a,int n,int parent)
{
	int child = parent * 2 + 1;
	while (child < n)
	{
		if (child + 1 < n && a[child + 1] > a[child])
		{
			++child;
		}

		if (a[child] > a[parent])
		{
			swap(&a[child], &a[parent]);
			parent = child;
			child = parent * 2 + 1;
		}
		else
		{
			break;
		}
	}
}

void HPPop(HP* php)
{
	assert(php);
	assert(!HPEmpty(php));

	swap(&php->a[0], &php->a[php->size-1]);
	php->size--;

	AdJustDowm(php->a,php->size,0);

}

HPDataType HPTop(HP* php)
{
	assert(php);
	return php->a[0];
}

bool HPEmpty(HP* php)
{
	assert(php);
	return php->size == 0;
}

int HPSize(HP* php)
{
	assert(php);
	return php->size;
}

void PrintTopK(int* a, int n, int k)
{
	while (!HPEmpty(a) && k--)
	{
		printf("%d ", HPTop(a));
		HPPop(a);
	}
	printf("\n");
}